package com.siping.并发.练习题;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author Yang Xu
 * @date 2021/9/6 10:43
 * @description: 通过一个计数器来实现的，计数器的初始值是线程的数量。每当一个线程执行完毕后，计数器的值就-1，
 *               当计数器的值为0时，表示所有线程都执行完毕，然后在闭锁上等待的线程就可以恢复工作了。
 *
 */
public class CountDownLatchTest {

    public static void main(String[] args) {
        CountDownLatch downLatch = new CountDownLatch(5);
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                downLatch.countDown();
                System.out.println(downLatch.getCount());
                System.out.println(Thread.currentThread().getName() + "等待执行任务...");
                try {
                    TimeUnit.SECONDS.sleep(1);
                    downLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在执行任务...");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行完毕...");
            }, "t" + i).start();
        }

    }
}
